<?php


namespace app\controller\admin\school;


use app\common\CacheKey;
use app\common\exception\ApiException;
use app\common\RedisKey;
use app\controller\admin\BaseAdminController;

use app\facade\RedisLocationFacade;
use app\model\config\RegionModel;
use app\model\school\SchoolModel;
use app\model\school\SchoolOrderModel;
use app\service\utils\QqMapService;
use app\service\utils\RegionService;
use think\App;

class SchoolController extends BaseAdminController
{

    function setModel()
    {
        return new SchoolModel();
    }

    function setWithModel()
    {
        return ['region'];
    }

    function setSearch()
    {
        return [
            'like' => ['name', 'region.name' => 'city_name'],
            '=' => ['is_recommend','city_id']
        ];
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    public function getList()
    {
        try {
            $list = parent::getList()->each(function ($item) {
                // 成功人数
                $item['success_num'] = SchoolOrderModel::where('school_id', $item['id'])
                    ->whereIn('status', [2, 3, 4, 6])
                    ->count();
                // 取消人数
                $item['cancel_num'] = SchoolOrderModel::where('school_id', $item['id'])
                    ->whereIn('status', [5])
                    ->count();
                $item['city'] = [(string)$item['province_id'], (string)$item['city_id'], (string)$item['area_id']];
            });
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }

    }

    public function save()
    {
        try {
            $id = $this->request->param('id', '', 'trim');
            $city = $this->request->param('city', '', 'trim');
            $name = $this->request->param('name', '', 'trim');
            $img = $this->request->param('img', '', 'trim');
            $address = $this->request->param('address', '', 'trim');
            $tel = $this->request->param('tel', '', 'trim');
            $isRecommend = $this->request->param('is_recommend', 0, 'int');
            $recommendReason = $this->request->param('recommend_reason', '', 'trim');
            $bus_img = $this->request->param('bus_img', '', 'trim');
            $way_img = $this->request->param('way_img', '', 'trim');
            $record_img = $this->request->param('record_img', '', 'trim');
            $front_img = $this->request->param('front_img', '', 'trim');
            $back_img = $this->request->param('back_img', '', 'trim');
            $num = $this->request->param('num', '', 'trim');
            if (!$city) {
                throw new ApiException('请选择所在城市');
            }
            if (!$name) {
                throw new ApiException('请填写驾校名称');
            }
            if (!$img) {
                throw new ApiException('请上传驾校照片');
            }
            if (!$address) {
                throw new ApiException('请填写驾校详细地址');
            }
            $regionService = new RegionService();
            $cityAddress = $regionService->getAddress($city[0], $city[1] ?? 0, $city[2] ?? 0);
            if (!$id) {
                $qqMapService = new QqMapService();
                $result = $qqMapService->getCoordinate($address);
                $lng = $result['lng'];
                $lat = $result['lat'];
                $data = [
                    'province_id' => $city[0],
                    'city_id' => $city[1] ?? 0,
                    'area_id' => $city[2] ?? 0,
                    'name' => $name,
                    'img' => $img,
                    'address' => $address,
                    'lng' => $lng,
                    'lat' => $lat,
                    'tel' => $tel,
                    'is_recommend' => $isRecommend == 1 ? time() : 0,
                    'recommend_reason' => $recommendReason,
                    'bus_img' => $bus_img,
                    'way_img' => $way_img,
                    'record_img' => $record_img,
                    'front_img' => $front_img,
                    'back_img' => $back_img,
                    'num' => $num,
                ];
                $model = $this->setModel();
                $model->save($data);

                RedisLocationFacade::setSchoolLocationToRedis(RedisKey::ALL_SCHOOL_LIST, $model->id, $data['lng'], $data['lat']);
            } else {
                $info = $this->setModel()->find($id);
                if (!$info) {
                    throw new \Exception('信息不存在');
                }
                $qqMapService = new QqMapService();
                $result = $qqMapService->getCoordinate($address);

                $lng = $result['lng'];
                $lat = $result['lat'];
                $info->address = $address;
                $info->lng = $lng;
                $info->lat = $lat;
                $info->province_id = $city[0];
                $info->city_id = $city[1] ?? 0;
                $info->area_id = $city[2] ?? 0;
                RedisLocationFacade::setSchoolLocationToRedis(RedisKey::ALL_SCHOOL_LIST, $id, $lng, $lat);
                $info->name = $name;
                $info->img = $img;
                $info->tel = $tel;
                $info->is_recommend = $isRecommend == 1 ? time() : 0;
                $info->recommend_reason = $recommendReason;
                $info->bus_img = $bus_img;
                $info->way_img = $way_img;
                $info->record_img = $record_img;
                $info->front_img = $front_img;
                $info->back_img = $back_img;
                $info->num = $num;
                $info->save();
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function getArr()
    {
        $where = [];
        $cityId = $this->request->param('city_id', 0);
        if ($cityId) {
            $where [] = ['city_id', '=', $cityId];
        }
        $arr = $this->setModel()->where($where)->select();
        return $this->success($arr);
    }
}